package com.example.home_app.base


import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import androidx.fragment.app.FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
import com.android.frame.mvp.CommonBaseFragment
import com.android.util.threadPool.ThreadPoolManager
import com.example.home_app.R
import com.example.home_app.adapter.Equipment
import com.example.home_app.http.base.cityweather.City_weather
import com.example.home_app.base.activity.SetActivity
import com.example.home_app.base.equipmentFragment.AllSbFragment

import com.example.home_app.base.equipmentFragment.BathroomSbFragment
import com.example.home_app.base.equipmentFragment.HomeSbFragment
import com.example.home_app.base.equipmentFragment.KitchenSbFragment
import com.example.home_app.databinding.FragmentWidgetBinding
import com.example.home_app.util.Json
import com.example.home_app.util.Location
import com.example.home_app.util.State
import com.example.home_app.util.State.City
import com.example.home_app.util.State.fengli
import com.example.home_app.util.State.shidu
import com.example.home_app.util.State.tianqi
import com.example.home_app.util.State.wendu
import com.example.home_app.util.Utils
import com.google.android.material.tabs.TabLayout
import okhttp3.*
import java.io.IOException
import java.lang.ref.WeakReference
import java.util.*
import java.util.concurrent.TimeUnit


/**
 * Created by xuzhb on 2019/9/7
 * Desc:控件篇
 */
class WidgetFragment : CommonBaseFragment<FragmentWidgetBinding>() {

    companion object {
        fun newInstance() = WidgetFragment()

    }
    private val mFragmentList: MutableList<Fragment> = mutableListOf(
        AllSbFragment.newInstance(),
        HomeSbFragment.newInstance(),
        KitchenSbFragment.newInstance(),
        BathroomSbFragment.newInstance()
    )
    private val mTitleList: MutableList<String> = mutableListOf("所有设备", "房间", "厨房", "浴室")
    override fun handleView(savedInstanceState: Bundle?) {
        needLazyLoadData()
        initBottomNavigationBar()
        Location.initMap()
        ThreadPoolManager.instance.getScheduledThreadPool().schedule(Runnable {
            if (City == "定位"){
                showToast("定位启动识别，请查看权限是非打开!\n请手动定位")
                Location.initMap()
            }else{
                getAsync()
            }


        }, 3, TimeUnit.SECONDS)

    }
    //初始化底部导航栏
    private fun initBottomNavigationBar() {
    //tab_layout.setTabMode(TabLayout.MODE_FIXED)//不可以轮动
        for (i in mTitleList.indices) {
            binding.tabLayout.addTab(binding.tabLayout.newTab().setText(mTitleList[i]))
        }
        binding.viewPager.adapter = Equipment(childFragmentManager,
            mFragmentList as ArrayList<Fragment>, mTitleList)
        binding.tabLayout.setupWithViewPager(binding.viewPager)

        binding.tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            //选中之后再次点击Tab时触发
            override fun onTabReselected(tab: TabLayout.Tab?) {
            }

            //切换Tab时触发，返回切换前的Tab
            override fun onTabUnselected(tab: TabLayout.Tab?) {
            }

            //选择某一个Tab时触发，返回切换后的Tab
            override fun onTabSelected(tab: TabLayout.Tab?) {
                //解决ViewPager + Fragment，点击tab切换时造成的闪屏问题
                tab?.let {
                    // 默认切换的时候，会有一个过渡动画，设为false后，取消动画，直接显示
                    binding.viewPager.setCurrentItem(it.position, true)
                }
            }

        })

    }

    override fun initListener() {
        binding.TextViewDingWei.setOnClickListener {
            Handler(Looper.getMainLooper()).postDelayed({
                if (City == "定位"){
                    Location.initMap()
                }else{
                    getAsync()
                    showToast("定位更新新成功")
                }
            }, 200)

        }
        //参数设置
        binding.ViewAdd.setOnClickListener {
            startActivity(SetActivity::class.java)
        }

    }

    private var okHttpClient: OkHttpClient? = null
    /**
     * 获取网络数据
     */
    private fun getAsync() {
        okHttpClient = OkHttpClient()
        val request = Request.Builder()
            .url(
                "http://restapi.amap.com/v3/weather/weatherInfo?" + "key=" + State.GD_ApiKey +
                        "&" + "city=" + City
            )
            .build()
        val call = okHttpClient !!.newCall(request)
        call.enqueue(object : Callback {
            @Throws(IOException::class)
            override fun onResponse(call: Call, response: Response) {
                try {
                    /*response.body().string()中的 (.string)只能使用一次*/
                    val responseData = response.body() !!.string()
                    val city_weather = Json.gson?.fromJson(responseData, City_weather::class.java)
                    val city_weatherData = city_weather?.getLives()
                    wendu = city_weatherData !![0].getTemperature().toString() + "℃"
                    shidu = city_weatherData[0].getHumidity().toString() + "%RH"
                    fengli =
                        city_weatherData[0].getWinddirection() + city_weatherData[0].getWindpower()
                    tianqi = (city_weatherData[0].getWeather()) !!
                    Handler(Looper.getMainLooper()).postDelayed({
                        binding.TextViewDingWei.text = City
                        binding.tianqi.text = tianqi
                        binding.fengli.text = fengli
                        binding.wendu.text = wendu
                        binding.shidu.text = shidu
                    }, 200)
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }

            override fun onFailure(call: Call, e: IOException) {}
        })
    }


}